package zcw.com.lib_leet_code;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by 朱城委 on 2021/7/22.<br><br>
 *
 * LRU 缓存机制
 */
public class Topic146 {

    public static void main(String[] args) {
        LRUCache cache = new LRUCache(2);

        cache.put(1, 1); // cache is {1=1}
        cache.put(2, 2); // cache is {1=1, 2=2}
        cache.get(1);    // return 1
        cache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
        cache.get(2);    // returns -1 (not found)
        cache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
        cache.get(1);    // return -1 (not found)
        cache.get(3);    // return 3
        cache.get(4);    // return 4
    }

    private static class LRUCache {

        private final LinkedHashMap<Integer, Integer> cache;

        public LRUCache(int capacity) {
            cache = new LinkedHashMap<Integer, Integer>(capacity, 0.75F, true) {
                @Override
                protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
                    return size() > capacity;
                }
            };
        }

        public int get(int key) {
            return cache.getOrDefault(key, -1);
        }

        public void put(int key, int value) {
            cache.put(key, value);
        }
    }
}
